//
//  RegistrationView.m
//  VivaModa
//
//  Created by Sergey on 2/28/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "RegistrationView.h"
#import "register_cell.h"


@interface RegistrationView (){
    Boolean keyboardIsShowing;
    CGRect keyboardBounds;
    NSArray *array_step_reg;
    UITextField *test_textField;
}
@property (strong, nonatomic) NSArray *dataLocation;
@property (strong, nonatomic) NSMutableArray *sortedArrayRegion;
@property (strong, nonatomic) NSMutableArray *sortedArrayCountry;

- (void)resizeViewControllerToFitScreen;
@end

@implementation RegistrationView
@synthesize tableView;
@synthesize pickerView;

@synthesize dataLocation;
@synthesize sortedArrayRegion;
@synthesize sortedArrayCountry;


@synthesize locateData;
@synthesize connection_locate;
@synthesize connection_registration;
@synthesize registrationData;
@synthesize button_register;

bool showed_picker;
int current_id_country = -1;
int last_country_id = 0;/// что б небыло в Украине Москвы
int last_zone_id = 0;///


NSString *text_region;
NSString *text_strana;

NSString *text_name;
NSString *text_second_name;
NSString *text_email;
NSString *text_adress;
NSString *text_town;
NSString *text_telephone;
NSString *text_pass;
NSString *text_conf_pass;
NSString *text_kod;
bool subscribe_user;


int id_button;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    text_region = @"";
    text_strana = @"";
    
    [self.tableView reloadData];
    
 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}


- (void)viewWillDisappear:(BOOL)animated {
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    [self addCustomBackButton];
    [self setNavigationTitle];
    
    [self hidePicker:NO];
    
    subscribe_user = YES;
    
    sortedArrayRegion = [[NSMutableArray alloc] initWithCapacity:1];
    sortedArrayCountry = [[NSMutableArray alloc] initWithCapacity:1];
    
    [self getLocationData];
    
    
    /*self.dataRegion = [NSArray arrayWithObjects:
                       @"Objective C",
                       @"C",
                       @"C++",
                       @"Java",
                       @"Pascal",
                       @"Delphi", nil];
    
    
    self.dataStrana = [NSArray arrayWithObjects:
                       @"Украина",
                       @"Россия",
                       @"Беларусь",
                        nil];
    */
    array_step_reg = @[
                       @{@"name_step":@"*Имя",@"id":@"1"},
                       @{@"name_step":@"Фамилия",@"id":@"2"},
                       @{@"name_step":@"*e-mail",@"id":@"3"},
                       @{@"name_step":@"*Адресс",@"id":@"4"},
                       @{@"name_step":@"*Город",@"id":@"5"},
                       @{@"name_step":@"*Страна",@"id":@"6"},
                       @{@"name_step":@"Регион",@"id":@"7"},
                       @{@"name_step":@"Телефон",@"id":@"8"},
                       @{@"name_step":@"*Пароль",@"id":@"9"},
                       @{@"name_step":@"*Подтверд. пароль",@"id":@"10"},
                       @{@"name_step":@"Код",@"id":@"11"},
                       @{@"name_step":@"Подписка на новости магазина",@"id":@"12"}
                       ];
    
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    [self.button_register setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.button_register setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];
}


//register_cell_subscribe

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [array_step_reg count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"register_cell";
    
    
    static NSString *CellIdentifier_s = @"register_cell_subscribe";
    register_cell *cell_subscribe = nil;
    
    cell_subscribe = (register_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier_s];
    if(!cell_subscribe)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"register_cell_subscribe" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[register_cell class]])
            {
                cell_subscribe = (register_cell *)currentObject;
                break;
            }
        }
    }

    
    
    
    
    
    
    register_cell *cell = nil;
    cell = (register_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"register_cell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[register_cell class]])
            {
                cell = (register_cell *)currentObject;
                break;
            }
        }
    }
    
    int id_cell = [[[array_step_reg objectAtIndex:indexPath.row] objectForKey:@"id"] integerValue];
    
    
    switch (id_cell) {
        case 1:{
            cell.text_field.text = text_name;
            break;}
        case 2:{
            cell.text_field.text = text_second_name;
            break;}
        case 3:{
            cell.text_field.text = text_email;
            break;}
        case 4:{
            cell.text_field.text = text_adress;
            break;}
        case 5:{
            cell.text_field.text = text_town;
            break;}
        case 6:{
            cell.text_field.text = text_strana;
            break;}
        case 7:{
            cell.text_field.text = text_region;
            break;}
        case 8:{
            cell.text_field.text = text_telephone;
            break;}
        case 9:{
            cell.text_field.text = text_pass;
            break;}
        case 10:{
            cell.text_field.text = text_conf_pass;
            break;}
        case 11:{
            cell.text_field.text = text_kod;
            break;}
        case 12:{
            cell_subscribe.name_steps.text = [[array_step_reg objectAtIndex:indexPath.row] objectForKey:@"name_step"];
            cell_subscribe.subscribe.on = subscribe_user;
            cell_subscribe.subscribe.tag = 50;
            [cell_subscribe.subscribe addTarget:self action:@selector(changeSubscribe:) forControlEvents:UIControlEventValueChanged];
            cell_subscribe.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell_subscribe;
            break;}
        default:
            break;
    }
    
    
    
    
    if (id_cell==6 || id_cell==7) {
        cell.button_cell.tag = id_cell;
        cell.button_cell.hidden = NO;
        [cell.button_cell addTarget:self action:@selector(touchOpenPicker:) forControlEvents:UIControlEventTouchUpInside];
        //cell.button_cell.backgroundColor = [UIColor redColor];
    }else{
        cell.button_cell.hidden = YES;
    }
    
        
    cell.name_steps.text = [[array_step_reg objectAtIndex:indexPath.row] objectForKey:@"name_step"];
    
    NSString* name_step = [[array_step_reg objectAtIndex:indexPath.row] objectForKey:@"name_step"];
    NSRange range = [name_step rangeOfString:@"*"];
    NSMutableAttributedString* attrStr2 = [NSMutableAttributedString attributedStringWithString:name_step];
    [attrStr2 setFont:[UIFont systemFontOfSize:14]];
    [attrStr2 setTextColor:[UIColor blackColor]];
    [attrStr2 setTextColor:[UIColor redColor] range:range];
    cell.name_steps.attributedText = attrStr2;
    
    
    
    cell.text_field.tag = id_cell;
    cell.text_field.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}





#pragma mark -
#pragma mark Keyboard Handling

- (void)keyboardWillShow:(NSNotification *)notification {
	NSDictionary *userInfo = [notification userInfo];
	[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
	keyboardIsShowing = YES;
	[self resizeViewControllerToFitScreen];
}

- (void)keyboardWillHide:(NSNotification *)note {
	keyboardIsShowing = NO;
	keyboardBounds = CGRectMake(0, 0, 0, 0);
	[self resizeViewControllerToFitScreen];
}


- (void)resizeViewControllerToFitScreen {
	// Needs adjustment for portrait orientation!
	CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
	CGRect frame = self.tableView.frame;
	frame.size.height = applicationFrame.size.height - self.tabBarController.tabBar.frame.size.height - self.navigationController.navigationBar.frame.size.height;
    
	if (keyboardIsShowing)
		frame.size.height -= (keyboardBounds.size.height-50);
    
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
	[UIView setAnimationDuration:0.3f];
	self.view.frame = frame;
	[UIView commitAnimations];
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}




- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    int id_cell = textField.tag;
    
    NSString *text;
    if (range.length<1) {
        
        text = [NSString stringWithFormat:@"%@%@",textField.text,string];
    }else{
        text = [textField.text substringToIndex:[textField.text length] - 1];
        //text = [NSString stringWithFormat:@"%@",textField.text];
    }
    
    
    
    
    switch (id_cell) {
        case 1:{
            text_name = text;
            break;}
        case 2:{
            text_second_name = text;
            break;}
        case 3:{
            text_email = text;
            break;}
        case 4:{
            text_adress = text;
            break;}
        case 5:{
            text_town = text;
            break;}
        case 6:{
            text_strana = text;
            break;}
        case 7:{
            text_region = text;
            break;}
        case 8:{
            text_telephone = text;
            break;}
        case 9:{
            text_pass = text;
            break;}
        case 10:{
            text_conf_pass = text;
            break;}
        case 11:{
            text_kod = text;
            break;}
        default:
            break;
    }

    return YES;
}

-(void) textFieldDidBeginEditing:(UITextField *)textField {
    
    [self hidePicker:showed_picker];
    if (textField.tag==2) {
        //[test_textField resignFirstResponder];
        //[textField resignFirstResponder];
        //[self performSelector:@selector(openPicker:) withObject:self afterDelay:0.5];
    }
    test_textField = textField;
    
    CGPoint pnt = [self.tableView convertPoint:textField.bounds.origin fromView:textField];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:pnt];
    
    [self performSelector:@selector(aaaap:) withObject:path afterDelay:0.1];
}

-(void)aaaap:(NSIndexPath*)path{
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

-(void)upScrolFromPicker:(NSIndexPath*)path{
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView
numberOfRowsInComponent:(NSInteger)component
{
    if (id_button==6) {
        return sortedArrayCountry.count;
    }else{
        return sortedArrayRegion.count;
    }
    
}

- (NSString *)pickerView:(UIPickerView *)thePickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    if (id_button==6) {
        return [[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_name"];
    }else{
        return [[sortedArrayRegion objectAtIndex:row] objectForKey:@"name_zone"];
    }
}



-(void)touchOpenPicker:(id)sender{
    [test_textField resignFirstResponder];
    [self openPicker:self];
    
    UIButton *button = (UIButton*)sender;
    id_button = [sender tag];
    
    CGPoint pnt = [self.tableView convertPoint:button.bounds.origin fromView:button];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:pnt];
    
    [pickerView reloadAllComponents];
    [self performSelector:@selector(upScrolFromPicker:) withObject:path afterDelay:0.1];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (id_button==6) {
        text_strana = [[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_name"];
        
        current_id_country = [[[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_id"] integerValue];
        
        //NSLog(@"11 %@",[[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_id"]);
        
        if (last_country_id!=current_id_country) {
            text_region= @"";
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:id_button inSection:0];
            NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
        }
        
        [self sortRegionWithIdCountry:current_id_country];
        

    }else{
        
        last_zone_id = [[[sortedArrayRegion objectAtIndex:row] objectForKey:@"zone_id"] integerValue];
        text_region = [[sortedArrayRegion objectAtIndex:row] objectForKey:@"name_zone"];
        
    }
    
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:id_button-1 inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

}


-(IBAction)openPicker:(id)sender{
    if ([sortedArrayCountry count]>0 && [sortedArrayRegion count]>0) {
        [self hidePicker:NO];
        showed_picker = YES;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, self.view.frame.size.height - pickerView.frame.size.height/2);
        [UIView commitAnimations];
    }
}


-(void)hidePicker:(BOOL)animate{
    showed_picker = NO;
    if (animate) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, [UIScreen mainScreen].bounds.size.height+pickerView.frame.size.height);
        [UIView commitAnimations];
    }else{
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, [UIScreen mainScreen].bounds.size.height+pickerView.frame.size.height);
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (showed_picker) {
        [self hidePicker:YES];
    }
    [test_textField resignFirstResponder];
}



-(IBAction)changeSubscribe:(id)sender{
    UISwitch *switch_view = (UISwitch*)sender;
    //NSLog(@"state = %i",switch_view.on);
    subscribe_user = switch_view.on;
}


-(IBAction)registerUser:(id)sender{
    if ([text_pass isEqualToString:text_conf_pass]) {
        if ([text_pass length]>5) {
            //NSLog(@"REGISTER DATA");
            //NSLog(@"text_name = %@",text_name);
            //NSLog(@"text_second_name = %@",text_second_name);
            //NSLog(@"text_email = %@",text_email);
            //NSLog(@"text_adress = %@",text_adress);
            //NSLog(@"text_town = %@",text_town);
            //NSLog(@"text_region = %@",text_region);
            //NSLog(@"text_strana = %@",text_strana);
            //NSLog(@"text_telephone = %@",text_telephone);
            //NSLog(@"text_pass = %@",text_pass);
            //NSLog(@"text_kod = %@",text_kod);
            //NSLog(@"subscribe_user = %i",subscribe_user);
            
            
            
            if ([text_name length]>0 && [text_email length]>0 && [text_adress length]>0 && [text_town length]>0 && [text_strana length]>0) {
                
                NSString *pass = [text_pass MD5];
                
                NSString* params = [NSString stringWithFormat:@"email=%@&password=%@&first_name=%@&last_name=%@&telephone=%@&newsletter=%i&id_zone=%i&id_country=%i&streat_adress=%@&city=%@",text_email,pass,text_name,text_second_name,text_telephone,subscribe_user,last_zone_id,last_country_id,text_adress,text_town]; // задаем параметры POST запроса
                
                
                //NSLog(@"params = %@",params);
                
                
                NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/registration.php"]; // куда отправлять
                NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
                request.HTTPMethod = @"POST";
                request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
                
                connection_registration = [NSURLConnection connectionWithRequest:request delegate:self];
                [self displayActivityView];
                if (connection_registration) {
                    self.registrationData = [NSMutableData data];
                }

                
            }else{
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Заполнены не все обязательные поля (*)."];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                }];
                
                [alert show];
            }

            
            
            
        }else{
            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Длинна пароля должна быть не меньше 6 символов"];
            [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            }];
            
            [alert show];

        }
        
        
        
        
    }else{
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Не правильное подтверждение пароля"];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        }];
        
        [alert show];
    }
    
    
    
    
    
}






-(void)getLocationData{
        
    NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/get_location.php"]; // куда отправлять
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    connection_locate = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_locate) {
        self.locateData = [NSMutableData data];
    }
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (connection == connection_locate) {
        [locateData appendData:data];
    }else{
        if (connection == connection_registration) {
            [registrationData appendData:data];
        }
    }
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if (connection == connection_locate) {
        //NSString *result = [[NSString alloc] initWithData:userData encoding:NSUTF8StringEncoding];
        [self parseJSON:locateData fromRegistration:NO];
    }else{
        if (connection == connection_registration) {
            //NSString *result = [[NSString alloc] initWithData:registrationData encoding:NSUTF8StringEncoding];
            //NSLog(@"result = %@",result);
            [self parseJSON:registrationData fromRegistration:YES];
        }
    }
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data fromRegistration:(BOOL)from_reg{
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    NSArray * array_location = [json objectForKey:@"message"];
    
    if (from_reg) {
        if ([requestResultAutorization integerValue]==1) {
            if ([array_location count]>0) {
                
                
                //NSLog(@"array_loca = %@",array_location);
                
                
                [UserDefaults setObject:[[array_location objectAtIndex:0] objectForKey:@"user_id"] forKey:@"id_user"];
                [UserDefaults setObject:[[array_location objectAtIndex:0] objectForKey:@"first_name"] forKey:@"f_name_user"];
                [UserDefaults setObject:[[array_location objectAtIndex:0] objectForKey:@"last_name"] forKey:@"s_name_user"];
                
                
                [UserDefaults setObject:[[array_location objectAtIndex:0] objectForKey:@"adress"] forKey:@"u_adress"];
                [UserDefaults setObject:[[array_location objectAtIndex:0] objectForKey:@"city"] forKey:@"u_city"];
                [UserDefaults setObject:[[array_location objectAtIndex:0] objectForKey:@"id_country"] forKey:@"u_id_country"];
                [UserDefaults setObject:[[array_location objectAtIndex:0] objectForKey:@"id_zone"] forKey:@"u_id_zone"];
                
                
                
                [Singleton sharedMySingleton].neadCheckLogin = YES;
                
                [[Singleton sharedMySingleton] checkUser];
                
                
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Спасибо за регистрацию!"];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                }];
                [alert show];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else{
            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Сбой регистрации" message:[json objectForKey:@"message"]];
            [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            }];
            [alert show];
        }
    }else{
        if ([requestResultAutorization integerValue]==1) {
            if ([array_location count]>0) {
                dataLocation = array_location;
                [self sortCountryFromArray:array_location];;
            }else{
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации с сервером"];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                }];
                [alert show];
            }
        }else{
            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации с сервером"];
            [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            }];
            [alert show];
        }
    }
    
    
    [self removeActivityView];   
}




-(void)sortCountryFromArray:(NSArray*)array_data{
    if ([array_data count]>0) {
        [sortedArrayRegion removeAllObjects];
        NSSet * set = [NSSet setWithArray:[array_data valueForKey:@"country_id"]];
        NSMutableArray *sorted_array = [[set allObjects] mutableCopy];
        
        for (int j =0; j<[sorted_array count]; j++) {
            for (int i =0; i < [array_data count]; i++) {
                if ([[[array_data objectAtIndex:i] objectForKey:@"country_id"] integerValue]==[[sorted_array objectAtIndex:j]  integerValue]) {
                    NSString *id_country = [[array_data objectAtIndex:i] objectForKey:@"country_id"];
                    NSString *name_country = [[array_data objectAtIndex:i] objectForKey:@"country_name"];
                    NSString *id_zone = [[dataLocation objectAtIndex:i] objectForKey:@"zone_id"];
                    NSDictionary *dict = @{@"country_id" : id_country, @"country_name" : name_country,@"zone_id" : id_zone};
                    [sortedArrayCountry addObject:dict];
                    break;
                }
            }
        }
        
        if ([sortedArrayCountry count]>0) {
            current_id_country = [[[sortedArrayCountry objectAtIndex:0] objectForKey:@"country_id"] integerValue];
            [self sortRegionWithIdCountry:current_id_country];
        }
        
        //NSLog(@"sortedArrayCountry  = %@",sortedArrayCountry);
      
    }
}


-(void)sortRegionWithIdCountry:(int)id_country{
    [sortedArrayRegion removeAllObjects];
    
    NSDictionary *dict_clear = @{@"country_id" : @"0", @"name_zone":@"",@"zone_id":@"0"};
    [sortedArrayRegion addObject:dict_clear];
    
    for (int i =0; i < [dataLocation count]; i++) {
        if ([[[dataLocation objectAtIndex:i] objectForKey:@"country_id"] integerValue]==id_country) {
            NSString *id_country = [[dataLocation objectAtIndex:i] objectForKey:@"country_id"];
            NSString *name_zone = [[dataLocation objectAtIndex:i] objectForKey:@"name_zone"];
            NSString *id_zone = [[dataLocation objectAtIndex:i] objectForKey:@"zone_id"];
            NSDictionary *dict = @{@"country_id" : id_country, @"name_zone" : name_zone,@"zone_id" : id_zone};
            [sortedArrayRegion addObject:dict];
        }
    }
    last_country_id = id_country;
    //NSLog(@"sortedArrayRegion = %@",sortedArrayRegion);
}






- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(getLocationData) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}

#pragma mark Dejal activity

- (void)displayActivityView
{
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark

-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}


-(void)setNavigationTitle{
    UILabel *lblTitle = [[UILabel alloc] init];
    lblTitle.text = @"Регистрация";
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor colorWithRed:242.0/255.0 green:240.0/255.0 blue:234.0/255.0 alpha:1];
    
    lblTitle.font = [UIFont fontWithName:@"American Retro" size:27.0];
    [lblTitle sizeToFit];
    
    self.navigationItem.titleView = lblTitle;
}


-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 29)];
    //[backButton setImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 20, 20, 20) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Назад" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}

-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
